package com.gxy.learn.docx4j;

import com.gxy.learn.cu.utils.io.FileUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.docx4j.Docx4J;
import org.docx4j.TraversalUtil;
import org.docx4j.XmlUtils;
import org.docx4j.dml.wordprocessingDrawing.Inline;
import org.docx4j.finders.RangeFinder;
import org.docx4j.fonts.IdentityPlusMapper;
import org.docx4j.fonts.Mapper;
import org.docx4j.fonts.PhysicalFonts;
import org.docx4j.jaxb.Context;
import org.docx4j.openpackaging.exceptions.Docx4JException;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.docx4j.openpackaging.parts.WordprocessingML.BinaryPartAbstractImage;
import org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart;
import org.docx4j.wml.*;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;

/**
 * docx4j生成docx文件、pdf文件、docx转pdf、docx转图片 pdf转图片工具
 *
 * 有三种方式
 * 1 通过占位符
 *
 * <p>
 * 通过docx文件的书签、占位符替换变量
 * <p>
 * 通过占位符替换注意
 * * 通过占位符替换注意 -----------坑坑坑坑 直接再docx文件中进行修改占位符不一定会连续！！！-----------
 * ${var}必须是连续的，否则取不到变量。有时候取不到变量的时候可以抓换为xml然后查看你的变量是否是连续的
 * 可以通过如下方式解决 现在docx文件中写入占位符然后
 * 把当前docx文件用rar或zip打开，找到其中的 word/document.xml文件，修改占位符连续
 * <p>
 * 比如把
 * <w:r>
 * <w:t>${na</w:t>
 * </w:r>
 * <w:r>
 * <w:t>me}</w:t>
 * </w:r>
 * 修改为
 * <w:r>
 * <w:t>${name}</w:t>
 * </w:r>
 * 2、全部通过书签
 * 3、通过域变量
 *  通过域变量需要重写 docx4居中 XmlUtils 工具类中unmarshallFromTemplate方法 以适配域变量
 *  具体目录在 org.docx4j
 * @author gaoxueyong
 * @create at: 2021/12/28 下午15:02
 */
@Slf4j
public class DocxAndPdfAndImgUtils {
    private static WordprocessingMLPackage wordMLPackage;
    private static ObjectFactory factory;

    /**
     * 通过docx模板获取docx模板转换的图片
     *
     * @param templatePath 模板文件
     * @param mappings     要匹配的占位符数据
     * @param fileMapping  书签名称对于的文件
     * @return
     */
    public static List<byte[]> getPngByDocxTemplate(String templatePath, Map<String, String> mappings, Map<String, byte[]> fileMapping) {
        return pdfToImg(getPdfFile(templatePath, mappings, fileMapping));
    }

    /**
     * 通过模板获取转换后docx的二进制数组
     *
     * @param templatePath 模板文件
     * @param mappings     要匹配的占位符数据
     * @param fileMapping  书签名称对于的文件
     * @return
     */
    public static byte[] getDocxByTemplate(String templatePath, Map<String, String> mappings, Map<String, byte[]> fileMapping) {
        File docxFile = getDocxFile(templatePath, mappings, fileMapping);
        try {
            if (null == docxFile) {
                return null;
            }
            byte[] bytes = Files.readAllBytes(docxFile.toPath());
            if (docxFile.exists()) {
                docxFile.delete();
            }
            return bytes;
        } catch (IOException e) {
            log.error("获取文件失败");
            if (docxFile.exists()) {
                docxFile.delete();
            }
            return null;
        }
    }

    /**
     * 通过模板获取转换后pdf文件
     *
     * @param templatePath 模板文件
     * @param mappings     要匹配的占位符数据
     * @param fileMapping  书签名称对于的文件
     * @return
     */
    public static byte[] getPdfFile(String templatePath, Map<String, String> mappings, Map<String, byte[]> fileMapping) {
        try {
            File docxFile = getDocxFile(templatePath, mappings, fileMapping);
            if (null == docxFile) {
                return null;
            }
            WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(docxFile);
            Path pdf = Files.createTempFile(System.currentTimeMillis() + new Random().nextInt(100) + "", "pdf");
            File pdfFile = pdf.toFile();
            if (null == pdfFile) {
                log.error("创建文件失败");
                return null;
            }
            Docx4J.toPDF(wordMLPackage, new FileOutputStream(pdfFile));
            if (docxFile.exists()) {
                docxFile.delete();
            }
            byte[] bytes = Files.readAllBytes(pdf);
            if (pdfFile.exists()) {
                pdfFile.delete();
            }
            return bytes;
        } catch (Docx4JException e) {
            log.error("bookReplaceVarText error:Docx4JException ", e);
            return null;
        } catch (Exception e) {
            log.error("bookReplaceVarText error:Docx4JException ", e);
            return null;
        }
    }


    /**
     * 通过文件输入流获取pdf文档的二进制数组
     *
     * @param docxInputstream
     * @return
     */
    public static byte[] getPdfByte(InputStream docxInputstream) {
        try {
            if (null == docxInputstream) {
                return null;
            }
            WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(docxInputstream);
            Path pdf = Files.createTempFile(System.currentTimeMillis() + new Random().nextInt(100) + "", "pdf");
            File pdfFile = pdf.toFile();
            if (null == pdfFile) {
                log.error("创建文件失败");
                return null;
            }
            Docx4J.toPDF(wordMLPackage, new FileOutputStream(pdfFile));
            byte[] bytes = Files.readAllBytes(pdf);
            if (pdfFile.exists()) {
                pdfFile.delete();
            }
            return bytes;
        } catch (Docx4JException e) {
            log.error("bookReplaceVarText error:Docx4JException ", e);
            return null;
        } catch (Exception e) {
            log.error("bookReplaceVarText error:Docx4JException ", e);
            return null;
        }
    }

    /**
     * 通过模板获取转换后docx文件
     *
     * @param templatePath 模板文件
     * @param mappings     要匹配的占位符数据
     * @param fileMapping  书签名称对于的文件
     * @return
     */
    public static File getDocxFile(String templatePath, Map<String, String> mappings, Map<String, byte[]> fileMapping) {
        try {
            wordMLPackage = WordprocessingMLPackage.load(new File(templatePath));
            MainDocumentPart mainDocumentPart = wordMLPackage.getMainDocumentPart();
            if (MapUtils.isNotEmpty(mappings)) {
                mainDocumentPart.variableReplace(mappings);
            }

            factory = Context.getWmlObjectFactory();
            Document wmlDoc = (Document) mainDocumentPart.getJaxbElement();
            Body body = wmlDoc.getBody();
            // 提取正文中所有段落
            List<Object> paragraphs = body.getContent();
            // 提取书签并创建书签的游标
            RangeFinder rt = new RangeFinder("CTBookmark", "CTMarkupRange");
            new TraversalUtil(paragraphs, rt);
            // 遍历书签
            for (CTBookmark bm : rt.getStarts()) {
                log.info("标签名称:" + bm.getName());
                if (MapUtils.isEmpty(fileMapping)) {
                    break;
                }
                if (fileMapping.containsKey(bm.getName())) {
                    addImage(wordMLPackage, bm, fileMapping.get(bm.getName()));
                } else {
                    if (mappings.containsKey(bm.getName())) {
                        replaceText(bm, mappings.get(bm.getName()));
                    }
                }
            }
            wordMLPackage.setFontMapper(getFontMap());
            Path docx = Files.createTempFile(System.currentTimeMillis() + "", "docx");
            File docxFile = docx.toFile();
            Docx4J.save(wordMLPackage, docxFile);
            return docxFile;
        } catch (Docx4JException e) {
            log.error("bookReplaceVarText error:Docx4JException ", e);
            return null;
        } catch (Exception e) {
            log.error("bookReplaceVarText error:Docx4JException ", e);
            return null;
        }
    }


    /**
     * 在标签处插入内容
     *
     * @param bm
     * @param object
     * @throws Exception
     */
    public static void replaceText(CTBookmark bm, Object object) throws Exception {
        if (object == null) {
            return;
        }
        // do we have data for this one?
        if (bm.getName() == null) {
            return;
        }
        String value = object.toString();
        try {
            // Can't just remove the object from the parent,
            // since in the parent, it may be wrapped in a JAXBElement
            List<Object> theList = null;
            ParaRPr rpr = null;
            if (bm.getParent() instanceof P) {
                PPr pprTemp = ((P) (bm.getParent())).getPPr();
                if (pprTemp == null) {
                    rpr = null;
                } else {
                    rpr = ((P) (bm.getParent())).getPPr().getRPr();
                }
                theList = ((ContentAccessor) (bm.getParent())).getContent();
            } else {
                return;
            }
            int rangeStart = -1;
            int rangeEnd = -1;
            int i = 0;
            for (Object ox : theList) {
                Object listEntry = XmlUtils.unwrap(ox);
                if (listEntry.equals(bm)) {

                    if (((CTBookmark) listEntry).getName() != null) {

                        rangeStart = i + 1;

                    }
                } else if (listEntry instanceof CTMarkupRange) {
                    if (((CTMarkupRange) listEntry).getId().equals(bm.getId())) {
                        rangeEnd = i - 1;

                        break;
                    }
                }
                i++;
            }
            int x = i - 1;
            // if (rangeStart > 0 && x >= rangeStart) {
            // Delete the bookmark range
            for (int j = x; j >= rangeStart; j--) {
                theList.remove(j);
            }
            // now add a run
            R run = factory.createR();
            Text t = factory.createText();
            // if (rpr != null)
            // run.setRPr(paraRPr2RPr(rpr));
            t.setValue(value);
            run.getContent().add(t);
            // t.setValue(value);

            theList.add(rangeStart, run);
            // }
        } catch (ClassCastException cce) {
            log.error("error", cce);
        }
    }

    /**
     * 插入图片
     *
     * @param wPackage
     * @param bm
     * @param bytes
     */
    public static void addImage(WordprocessingMLPackage wPackage, CTBookmark bm, byte[] bytes) {
//        log.info("addImage :->{},{},{}", wPackage, bm);
        if (null == bytes) {
            return;
        }
        try {
            // 这儿可以对单个书签进行操作，也可以用一个map对所有的书签进行处理
            // 获取该书签的父级段落
            P p = (P) (bm.getParent());
            // R对象是匿名的复杂类型，然而我并不知道具体啥意思，估计这个要好好去看看ooxml才知道
            R run = factory.createR();
            // 读入图片并转化为字节数组，因为docx4j只能字节数组的方式插入图片
//            byte[] bytes = IOUtils.toByteArray(new FileInputStream(file));

            // InputStream is = new FileInputStream;
            // byte[] bytes = IOUtils.toByteArray(inputStream);
            // byte[] bytes = FileUtil.getByteFormBase64DataByImage("");
            // 开始创建一个行内图片
            BinaryPartAbstractImage imagePart = BinaryPartAbstractImage.createImagePart(wPackage, bytes);
//
//            ImageInfo imageInfo = imagePart.getImageInfo();
//            ImageSize imageSize = new ImageSize();
//            imageSize.setSizeInPixels(1000,1000);
//            imageInfo.setSize(imageSize);
//            // createImageInline函数的前四个参数我都没有找到具体啥意思，，，，
//            // 最后一个参数是限制图片的宽度，缩放的依据
//            imagePart.setImageInfo(imageInfo);


//            Inline inline = imagePart.createImageInline(null, null, 0, 1, false, 2350)
            /**
             * maxWidth  缩放比例 这个可以自行调试 具体比例是多少 没看懂。。。
             */
            Inline inline = imagePart.createImageInline(null, null, 500, 800, false,5000);
            // 获取该书签的父级段落
            // drawing理解为画布？
            Drawing drawing = factory.createDrawing();
            drawing.getAnchorOrInline().add(inline);
            run.getContent().add(drawing);
            p.getContent().add(run);
        } catch (Exception e) {
            log.error("", e);
        }
    }

    /**
     * 解决转换后数据显示异常的问题
     *
     * @return
     */
    private static Mapper getFontMap() {
        Mapper fontMapper = new IdentityPlusMapper();
        fontMapper.put("隶书", PhysicalFonts.get("LiSu"));
        fontMapper.put("宋体", PhysicalFonts.get("SimSun"));
        fontMapper.put("微软雅黑", PhysicalFonts.get("Microsoft Yahei"));
        fontMapper.put("黑体", PhysicalFonts.get("SimHei"));
        fontMapper.put("楷体", PhysicalFonts.get("KaiTi"));
        fontMapper.put("新宋体", PhysicalFonts.get("NSimSun"));
        fontMapper.put("华文行楷", PhysicalFonts.get("STXingkai"));
        fontMapper.put("华文仿宋", PhysicalFonts.get("STFangsong"));
        fontMapper.put("仿宋", PhysicalFonts.get("FangSong"));
        fontMapper.put("幼圆", PhysicalFonts.get("YouYuan"));
        fontMapper.put("华文宋体", PhysicalFonts.get("STSong"));
        fontMapper.put("华文中宋", PhysicalFonts.get("STZhongsong"));
        fontMapper.put("等线", PhysicalFonts.get("SimSun"));
        fontMapper.put("等线 Light", PhysicalFonts.get("SimSun"));
        fontMapper.put("华文琥珀", PhysicalFonts.get("STHupo"));
        fontMapper.put("华文隶书", PhysicalFonts.get("STLiti"));
        fontMapper.put("华文新魏", PhysicalFonts.get("STXinwei"));
        fontMapper.put("华文彩云", PhysicalFonts.get("STCaiyun"));
        fontMapper.put("方正姚体", PhysicalFonts.get("FZYaoti"));
        fontMapper.put("方正舒体", PhysicalFonts.get("FZShuTi"));
        fontMapper.put("华文细黑", PhysicalFonts.get("STXihei"));
        fontMapper.put("宋体扩展", PhysicalFonts.get("simsun-extB"));
        fontMapper.put("仿宋_GB2312", PhysicalFonts.get("FangSong_GB2312"));
        fontMapper.put("新細明體", PhysicalFonts.get("SimSun"));
        return fontMapper;
    }

    /**
     * pdf 转图片
     *
     * @param pdfFile
     * @return
     */
    public static List<byte[]> pdfToImg(byte[] pdfFile) {
        PDDocument doc = null;
        List<byte[]> outFile = new ArrayList<>();
        try {
            doc = PDDocument.load(pdfFile);
            PDFRenderer render = new PDFRenderer(doc);
            int count = doc.getNumberOfPages();
            for (int i = 0; i < count; i++) {
                // 设置图片的分辨率
                BufferedImage image = render.renderImageWithDPI(i, 296);
                // 如果是PNG图片想要背景透明的话使用下面这个
                // BufferedImage image = render.renderImageWithDPI(i, 296,
                // ImageType.ARGB);
                Path png = Files.createTempFile(System.currentTimeMillis() + new Random().nextInt(1000) + "_" + i, "png");
                File pngFile = png.toFile();
                ImageIO.write(image, "PNG", pngFile);
                outFile.add(Files.readAllBytes(png));
                pngFile.delete();
            }
        } catch (IOException e) {
            log.error("pdf转换图片失败！");
        } finally {
            if (doc != null) {
                try {
                    doc.close();
                } catch (IOException e) {
                    log.error("关闭PDDocument失败");
                }
            }
            return outFile;
        }
    }


    public static void main(String[] args) throws IOException {
        String rootPath = DocxAndPdfAndImgUtils.class.getClassLoader().getResource("").getPath();
        String filePath = String.format("%stemplates/docx4jtemplate.docx", rootPath);
        Map<String, String> mappings = new HashMap<>();

        mappings.put("user.username", "小明不怕不怕啦");
        mappings.put("user.hobby", "爱玩dota");
        mappings.put("name", "巨馍蘸酱");
        mappings.put("sssss", "巨馍蘸酱");
        Map<String, byte[]> fileMapping = new HashMap<>();

        fileMapping.put("logo", Files.readAllBytes(new File( String.format("%simg/1.png", rootPath)).toPath()));
        fileMapping.put("pic", Files.readAllBytes(new File( String.format("%simg/12.png", rootPath)).toPath()));

        byte[] docxByTemplate = getDocxByTemplate(filePath, mappings, fileMapping);
        String docxPath = "/Users/gaoxueyong/Desktop/测试pdf.docx";
        FileUtils.writeBytesToFileNio(docxByTemplate,docxPath);

        String pdfPath = "/Users/gaoxueyong/Desktop/测试pdf.pdf";
        FileUtils.writeBytesToFileNio(getPdfByte(new FileInputStream(docxPath)), pdfPath);


        List<byte[]> bytes = pdfToImg(Files.readAllBytes(new File(pdfPath).toPath()));
        int i = 0;
        for (byte[] bytess : bytes) {
            FileUtils.writeBytesToFileNio(bytess, String.format("/Users/gaoxueyong/Desktop/测试pdf%s.png", i + ""));
            i++;
        }
    }
}